package com.gitee.cui.basic.create;

import com.gitee.cui.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 线程状态的演示
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/10 10:23
 **/
@Slf4j
public class ThreadStatus {

    private static final int MAX_TURN = 5;

    private static int threadNo = 1;

    private static List<Thread> threads = new ArrayList<>();


    private static void addStatusThread(Thread thread) {
        threads.add(thread);
    }

    private static void printThreadStatus() {
        for (Thread thread : threads) {
            log.info(thread.getName() + ", 状态为：{}", thread.getState());
        }
    }

    static class StatusThread extends Thread {

        public StatusThread() {
            super("statusThread-" + threadNo++);
            addStatusThread(this);
        }

        @Override
        public void run() {
            log.info(getName() +"，状态为：{}", getState());
            for (int i = 0; i < MAX_TURN; i++) {
                ThreadUtil.sleepMilliSeconds(500);
                printThreadStatus();
            }
            log.info("{} - 运行结束", getName());
        }
    }

    public static void main(String[] args) {
        addStatusThread(Thread.currentThread());

        // 创建三个线程，并打印线程的状态
        StatusThread thread1 = new StatusThread();
        log.info(thread1.getName() +", 状态为: {}", thread1.getState());
        StatusThread thread2 = new StatusThread();
        log.info(thread2.getName() +", 状态为: {}", thread2.getState());
        StatusThread thread3 = new StatusThread();
        log.info(thread3.getName() +", 状态为: {}", thread3.getState());

        // 依次启动三个线程
        thread1.start();
        ThreadUtil.sleepMilliSeconds(500);
        thread2.start();
        ThreadUtil.sleepMilliSeconds(500);
        thread3.start();

        ThreadUtil.sleepSeconds(100);
    }
}
